<?php

namespace Modules\ShopAdmin\Models;
use Modules\AuthAdmin\Services\QueryService;
use Modules\AuthAdmin\Services\CommonService;
use Modules\ShopAdmin\Models\ShopProductSpec as ShopProductSpecModel;
use Modules\ShopAdmin\Models\ShopProductType as ShopProductTypeModel;
use Modules\AuthAdmin\Models\AuthImage as AuthImageModel;
use Illuminate\Support\Facades\DB; 
class ShopProduct extends BaseApiModel
{
	/**
	 * @name  关联商品分类表   多对一
	 */
	 public function product_type_to()
    {
        return $this->belongsTo('Modules\ShopAdmin\Models\ShopProductType','product_type_id','id');
    }
	/**
	 * @name  商品规格   一对多
	 */
	 public function product_spec_to()
    {
        return $this->hasMany('Modules\ShopAdmin\Models\ShopProductSpec','product_id','id');
    }
	/**
	 * @name  商品评论   一对多
	 */
	 public function evaluate_to()
    {
        return $this->hasMany('Modules\ShopAdmin\Models\ShopOrderEvaluate','product_id','id');
    }
	/**
	 * @name  关联商品图片   一对一
	 */
	 public function image_one()
    {
        return $this->hasOne('Modules\AuthAdmin\Models\AuthImage','id','image_id');
    }
	/**
     * @name   状态:0=下架,1=上架,0和1修改为true或false
     * @param  int  $value
     * @return Boolean 
     */
    public function getStatusAttribute($value)
    {
        return $value==1?true:false;
    }
	/**
     * @name   是否精品推荐:0=否,1=是,0和1修改为true或false
     * @param  int  $value
     * @return Boolean 
     */
    public function getRecommendStatusAttribute($value)
    {
        return $value==1?true:false;
    }
	/**
     * @name   是否热卖单品:0=否,1=是,0和1修改为true或false
     * @param  int  $value
     * @return Boolean 
     */
    public function getBestStatusAttribute($value)
    {
        return $value==1?true:false;
    }
	/**
     * @name   更新时间为null时返回
     * @param  int  $value
     * @return Boolean 
     */
    public function getUpdatedAtAttribute($value)
    {
        return $value?$value:'';
    }
	/**
	 * @name  商品列表
	 * @param  data array 搜索数据
	 * @return  JSON
	 */
	public function product_data($data){
		$model = $this->query();
		$model = (new QueryService())->query_condition($model,$data,'name');
		if(isset($data['product_type_id']) && $data['product_type_id']>0){
			$model = $model->where('product_type_id',$data['product_type_id']);
		}	
		if(isset($data['recommend_status']) && $data['recommend_status']>=0){
			$model = $model->where('recommend_status',$data['recommend_status']);
		}
		if(isset($data['best_status']) && $data['best_status']>=0){
			$model = $model->where('best_status',$data['best_status']);
		}		
        $list = $model->select('id','name','product_type_id','status','recommend_status','best_status','image_id','sales','money','created_at','updated_at','sort')
				->where(['is_delete'=>0])
				->with([
					'product_type_to'=>function($query){
							$query->select('id','title');  
					},
					'image_one'=>function($query){
							$query->select('id','url','open');  
					}
				])
				->withCount(['evaluate_to'])
				->orderBy('sort','asc') 
				->orderBy('id','desc') 
				->paginate($data['pagesize'])
				->toArray(); 
		$list['data'] = $this->common_image_one($list['data']);
		return $this->api_success(['data'=>[
			'list'=>$list['data'],
			'total'=>$list['total']
		]]);
	}
	/**
	 * @name  添加
	 * @param  data array 添加的商品数据
	 * @return  JSON
	 */
	public function product_create($data){
		$data['content'] = (new CommonService())->remve_pic_url($data['content']);
		if($data['specs_status']==0){
			$product_spec = $data['product_spec'][0];
			unset($data['product_spec']);
			$data['created_at'] = date('Y-m-d H:i:s'); 
			$product_spec['created_at'] = date('Y-m-d H:i:s');
			DB::beginTransaction();
			try{
				$id = $this->insertGetId($data);
				$product_spec['product_id'] = $id;
				ShopProductSpecModel::insert($product_spec);
				DB::commit();
			}catch(\Exception $e){
				DB::rollBack();
				return $this->api_error();
			}	
		}else{
			$data['attrbute_list'] = json_encode($data['attrbute_list'],JSON_UNESCAPED_UNICODE);
			$product_spec = $data['product_spec'];
			unset($data['product_spec']);
			$data['created_at'] = date('Y-m-d H:i:s'); 
			DB::beginTransaction();
			try{
				$id = $this->insertGetId($data);
				
				foreach($product_spec as $k=>$v){
					$product_spec[$k]['sku'] = implode('|',$v['sku']);
					$product_spec[$k]['specs'] = json_encode($v['specs'],JSON_UNESCAPED_UNICODE);
					$product_spec[$k]['product_id'] = $id;
					$product_spec[$k]['created_at'] = date('Y-m-d H:i:s');
				}
				ShopProductSpecModel::insert($product_spec);
				DB::commit();
			}catch(\Exception $e){
				DB::rollBack();
				return $this->api_error();
			}
		}
		
		return $this->api_success();
	}
	/**
	 * @name  编辑页面
	 * @param  id int 商品id
	 * @return  JSON
	 */
	public function get_edit($id){
		$data = $this->select('id','bazaar_money','content','describe','image_id','images','money','name','postage','product_type_id','sort','specs_status','attrbute_list')
					->with([
						'image_one'=>function($query){
							$query->select('id','url','open');  
						},
						'product_spec_to'=>function($query){
							$query->select('id','product_id','specs','money','bazaar_money','cost_money','postage','stock','sales','sku');  
						}
					])->find($id);
		$CommonService = new CommonService();
		$http = $CommonService->get_http_type();
		if(isset($data['image_one']) && $data['image_one']){
			if($data['image_one']['open'] == 1){
				$data['image_url'] = $http.$data['image_one']['url'];
			}else{
				$data['image_url'] = $data['image_one']['url'];
			}
		}
		unset($data['image_one']);
		$images_arr = [];
		if($data['images']){
			$images = AuthImageModel::whereIn('id',explode('|',$data['images']))->select('id','open','url')->get()->toArray();
			foreach($images as $k=>$v){
				if($v['open'] == 1){
					$images_arr[] = [
						'id'=>$v['id'],
						'name'=>$http.$v['url'],
						'url'=>$http.$v['url']
					];
				}else{
					$images_arr[] = [
						'id'=>$v['id'],
						'name'=>$v['url'],
						'url'=>$v['url']
					];
				}
			}
		}
		$data['images_arr'] = $images_arr;
		$data['product_type_id_arr'] = (new ShopProductTypeModel())->id_arr($data['product_type_id']);
		$data['attrbute_key_list'] = json_decode($data['attrbute_list'],true);
		foreach($data['product_spec_to'] as $k=>$v){
			$data['product_spec_to'][$k]['specs'] = json_decode($v['specs'],true);
		}
		$data['content'] = $CommonService->replace_pic_url($data['content']);
		return $this->api_success([
			'data'=>$data
		]);
	}
	/**
	 * @name  编辑
	 * @param  data array 编辑的商品数据
	 * @return  JSON
	 */
	public function product_update($data){
		$product_data = [
			'product_type_id'=>$data['product_type_id'],
			'name'=>$data['name'],
			'describe'=>$data['describe'],
			'image_id'=>$data['image_id'],
			'images'=>$data['images'],
			'sort'=>$data['sort'],
			'money'=>$data['product_spec_to'][0]['money'],
			'bazaar_money'=>$data['product_spec_to'][0]['bazaar_money'],
			'postage'=>$data['product_spec_to'][0]['postage'],
			'content'=>(new CommonService())->remve_pic_url($data['content']),
			'sales'=>0,
			'updated_at'=> date('Y-m-d H:i:s')
		];
		DB::beginTransaction();
		try{
			foreach($data['product_spec_to'] as $k=>$v){
				$product_data['sales'] = $product_data['sales'] + $v['sales'];
				ShopProductSpecModel::where(['id'=>$v['id']])->update([
					'money'=>$v['money'],
					'bazaar_money'=>$v['bazaar_money'],
					'cost_money'=>$v['cost_money'],
					'postage'=>$v['postage'],
					'stock'=>$v['stock'],
					'sales'=>$v['sales'],
					'updated_at'=> date('Y-m-d H:i:s')
				]);
			}
			$this->where(['id'=>$data['id']])->update($product_data);
			DB::commit();
		}catch(\Exception $e){
			DB::rollBack();
			return $this->api_error();
		}
		return $this->api_success();
	}
}
